﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Way.Bus.Controllers;
using Way.Bus.WMS.Model;
using Way.EAP.DataAccess.Data;
using System.Data;
using Way.EAP.DataAccess.Entity;
using Way.Contract.Data;
using Way.Contract.Data.ControllerData;
using Way.Contract.MVC;
using Way.Bus.Model;
using System.Configuration;
using InterfaceService.DataAccess;

namespace Way.Bus.WMS.Controllers
{
    public class StockInfoMaterialsController : BusinessController
    {
        /// <summary>
        /// 库存产品管理控制器
        /// 创建人：柳强
        /// 创建时间：2012-01-09
        /// </summary>
        public StockInfoMaterialsController() : base(new StockInfoMaterials()) { }
        public StockInfoMaterialsController(IModel model) : base(model) { }

        public override bool IsReviewedState
        {
            get
            {
                return false;
            }
        }


        protected override string OnControllerName()
        {
            return "库存产品管理";
        }

        //菜单中url路径
        protected override string OnGetPath()
        {
            return "Views/WMS/Materials/StockInfoMaterials.htm";
        }
        //开发人
        protected override string OnGetAuthor()
        {
            return "";
        }
        //说明
        protected override string OnGetControllerDescription()
        {
            return "库存产品管理";
        }

        #region 初始化数据方法
        protected override void OnInitViewChildItem(Way.Contract.Data.ModelData data, Way.Contract.Data.ItemData item)
        {
            if (data.name.EndsWith("StockInfoMaterials"))
            {
                if (item.IsField("SENBATCHNO"))
                    item.title = "货物有效期";
                switch (item.field.ToLower())
                {
                    case "Code":
                        item.visible = true;
                        break;
                }
            }
            if (data.name.EndsWith("InfoInSequence"))
            {
                data.isadd = false;
                data.isedit = false;
                data.isremove = false;
                switch (item.field.ToLower())
                {
                    case "sequencecode":
                    case "rowindex":
                        item.visible = true;
                        break;
                    default:
                        item.visible = false;
                        break;
                }
            }
        }

        #endregion

        #region 导入/导出

        /// <summary>
        /// 是否支持导入功能
        /// </summary>
        public virtual bool IsImportIn { get { return true; } }

        [ActionCommand(name = "导入", title = "导入", index = 6, icon = "icon-down", isselectrow = false, onclick = "import1")]
        public void ImportExcel()
        {

        }

        #endregion

        protected override void OnEditing(Way.Contract.MVC.ControllerBase.SaveEvent item)
        {
            base.OnEditing(item);
            StockInfoMaterials info = item.Item as StockInfoMaterials;
            if (info.FREEZENUM >= 0 && info.FREEZENUM <= Convert.ToDouble(info.NUM))
            {
                //info.NUM -= info.FREEZENUM;
                //info.ISLOCK = true;
            }
            else
            {
                throw new Exception("请输入正确的冻结数量");
            }
        }

        protected override void OnReviewedData(BasicInfo info)
        {
            base.OnReviewedData(info);
        }

        protected override ActionCommand[] OnInitCommand(ActionCommand[] commands)
        {
            ActionCommand[] cmd = base.OnInitCommand(commands);
            //获取所有按钮集合
            foreach (ActionCommand ac in cmd)
            {
                if (ac.command == "add")
                {
                    ac.visible = false;
                }
                if (ac.command == "edit")
                {
                    ac.visible = false;
                }
                if (ac.command == "remove")
                {
                    ac.visible = false;
                }
                if (ac.command == "SubmitData")
                {
                    ac.visible = false;
                }
                if (ac.command == "OnSubmitData")
                {
                    ac.visible = false;
                }
                if (ac.command == "ReviewedData")
                {
                    ac.visible = false;
                }
                if (ac.command == "ImportExcel")
                {
                    ac.visible = IsImportIn;
                }
            }
            return cmd;
        }


        /// <summary>
        /// 库存表code(sm.code也就是产品ID)
        /// </summary>
        [WhereParameter]
        public string SmCode { get; set; }
        /// 库存表depotwbs(sm.depotwbs也就是货位的ID)
        [WhereParameter]
        public string SmDepotwbs { get; set; }
        /// 库存表portcode(sm.portcode（也就是托盘的id)
        [WhereParameter]
        public string SmPortcode { get; set; }
        /// 库存表batchno(sm.batchno)
        [WhereParameter]
        public string SmBatchno { get; set; }
        /// 库存表senbatchno(sm.senbatchno)
        [WhereParameter]
        public string SmSenbatchno { get; set; }
        /// 库存表Num(sm.Num)
        [WhereParameter]
        public string SmNum { get; set; }
        /// controller(0:入库，1：出库)
        [WhereParameter]
        public string controller { get; set; }
        /// OrderId
        [WhereParameter]
        public string OrderId { get; set; }

        /// OrderId
        [WhereParameter]
        public string IsReturn { get; set; }

        /// <summary>
        /// 单个入库
        /// </summary>
        /// <returns></returns>
        //[ActionCommand(name = "入库", title = "入库", index = 10, icon = "icon-ok", isalert = true)]
        public string OnePutin()
        {
            string returnStr = CheckPutInData(controller);
            StockInfoMaterials stockinfo = new StockInfoMaterials();
            EntityList<StockInOrder> listInorder = new EntityList<StockInOrder>(this.model.GetDataAction());
            StockInOrder tempInOrder = new StockInOrder();
            EntityList<StockOutOrder> listOutorder = new EntityList<StockOutOrder>(this.model.GetDataAction());
            StockOutOrder tempOutOrder = new StockOutOrder();
            if (returnStr != "Y")
                return returnStr;
            if (controller == "0")
            {
                controller = "入库";
                stockinfo.LASTINTIME = DateTime.Now;
                listInorder.GetData(" ID='" + OrderId + "'");
                tempInOrder = listInorder[0];
            }
            if (controller == "1")
            {
                controller = "出库";
                stockinfo.LASTOUTTIME = DateTime.Now;
                listOutorder.GetData(" ID='" + OrderId + "'");
                tempOutOrder = listOutorder[0];
                SmNum = SmNum.Replace("--", "");
                if (Convert.ToInt32(SmNum) > 0)
                    IsReturn = "1";
                SmNum = (Convert.ToInt32(SmNum) * (-1)).ToString();
            }
            stockinfo.Code = SmCode;
            //stockinfo.BATCHNO = SmBatchno;
            //stockinfo.SENBATCHNO = SmSenbatchno;
            stockinfo.DEPOTWBS = SmDepotwbs.ToString();
            stockinfo.PORTCODE = SmPortcode;
            stockinfo.NUM = Convert.ToDouble(SmNum);
            EntityList<Materials> list1 = new EntityList<Materials>(this.model.GetDataAction());
            list1.GetData(" ID='" + SmCode + "'");
            Materials tempMaterials = list1[0];
            stockinfo.MCODE = tempMaterials.Code;
            stockinfo.FMODEL = tempMaterials.FMODEL;
            EntityList<WareHouse> listwh = new EntityList<WareHouse>(this.model.GetDataAction());
            listwh.GetData(" ID='" + SmDepotwbs.ToString() + "'");
            if (listwh.Count > 0)
                stockinfo.WAREHOUSEID = listwh[0].PARENTID;
            putin(stockinfo, controller, this.model.GetDataAction());

            //出入库流水表插入数据
            string strSourceid = "";
            string strSourcecontroller = "";
            string strSourcecode= "";
            string strIntype = "0";
            if (controller == "入库") {
                strSourceid = tempInOrder.ID.ToString();
                strSourcecode = tempInOrder.Code;
                strIntype = "1";

                switch (tempInOrder.STOCKTYPE)
                {
                    ///调拨入库(暂时没用)
                    case 4:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.StockChangeInOrderController";
                        break;
                    ///其他入库
                    case 3:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.StockElseInOrderController";
                        break;
                    ///成品入库(暂时没用)
                    case 2:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.SFUnPurchaseOrderController";
                        break;
                    ///原料入库
                    case 0:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.StockPurchaseInOrderController";
                        break;
                    ///销售退货入库
                    case 1:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.StockReturnInOrderController";
                        break;
                }
            }
            if (controller == "出库")
            {
                strSourceid = tempOutOrder.ID.ToString();
                strSourcecode = tempOutOrder.Code;
                strIntype = "0";

                switch (tempOutOrder.STOCKTYPE)
                {
                    ///销售出库
                    case 0:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.SFSellOrderController";
                        break;
                    ///调拨出库
                    case 1:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.SFProduceOrderController";
                        break;
                    ///返工出库
                    case 2:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.SFUnPurchaseOrderController";
                        break;
                    ///其他出库
                    case 5:
                        strSourcecontroller = "Way.Bus.WMS.SF.Controllers.OtherOutOrderController";
                        break;
                }
            }

            string strsql1 = "select SUM(num) num from Acc_WMS_InfoMaterials where Code=" + tempMaterials.ID;
            DataTable dt = this.model.GetDataAction().GetDataTable(strsql1);
            string strnum = SmNum;
            if (dt.Rows[0]["num"].ToString() != "")
                strnum = dt.Rows[0]["num"].ToString();
            string str = string.Format("insert into Acc_WMS_InOutOrderList(SourceID,SourceController,SourceCode,MAT_NAME,MAT_CODE,FMODEL,BATCHNO,PORT_CODE,NUM,INTYPE,LASTOUTTIME,Remark,ORDERNO) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}')",
                strSourceid, strSourcecontroller, strSourcecode, tempMaterials.ID, tempMaterials.Code, tempMaterials.FMODEL, tempMaterials.BATCH, SmPortcode, SmNum, strIntype, DateTime.Now.ToString(), strnum, OrderId);

            this.model.GetDataAction().Execute(str);
            //同步
            synchronization();
            SmCode = "";
            SmDepotwbs = "";
            SmPortcode = "";
            SmBatchno = "";
            SmSenbatchno = "";
            SmNum = "";
            controller = "";
            IsReturn = "";
            return "Y";
        }

        public void synchronization()
        {
            try
            {
                EntityList<Materials> list1 = new EntityList<Materials>(this.model.GetDataAction());
                list1.GetData(" ID=" + SmCode);
                Materials ms = list1[0];
                DateTime dt = DateTime.Now;
                int dtYear = dt.Year;
                int dtMonth = dt.Month;
                int dtDay = dt.Day;
                string Rq = dtYear + "," + dtMonth + "," + dtDay;
                string Xh;
                string Bm;
                string Dwh;
                string Dwmc;
                string Pm;
                string Gg;
                string Rksl;
                string Rkdh;
                //入库
                if (controller == "入库")
                {
                    EntityList<StockInOrder> list2 = new EntityList<StockInOrder>(this.model.GetDataAction());
                    list2.GetData(" ID=" + OrderId);
                    StockInOrder sio = list2[0];
                    BusinessCustomer bc = new BusinessCustomer();
                    EntityList<BusinessCustomer> list3 = new EntityList<BusinessCustomer>(this.model.GetDataAction());
                    if (sio.CLIENTNO != "")
                        list3.GetData(" ID=" + sio.CLIENTNO);
                    if (list3.Count > 0)
                    {
                        bc = list3[0];
                    }
                    string strCon1 = ConfigurationManager.AppSettings["FOXIPKC"].ToString() + "IPSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    DataTable dt1 = BusFoxProHelper.ExecuteDataTable(strCon1, CommandType.Text, "SELECT MAX(Xh) as Xh from Ipsjk");
                    //Xh = dt1.Rows[0]["Xh"].ToString();
                    Xh = sio.Code;
                    Bm = ms.Code;
                    Gg = ms.FNAME;
                    Dwh = bc.Code;
                    Dwmc = bc.CUSTOMERNAME;
                    Pm = "鸭产品";
                    Rksl = SmNum;
                    Rkdh = sio.Code;
                    string strSql = "";
                    string strOldSql = "SELECT * from ipsjk where Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Rksl>0";
                    DataTable dtOldIpkc = BusFoxProHelper.ExecuteDataTable(strCon1, CommandType.Text, strOldSql);
                    decimal oldNum = 0;
                    if (dtOldIpkc.Rows.Count > 0)
                    {
                        //更新仓库
                        oldNum = Convert.ToDecimal(dtOldIpkc.Rows[0]["Rksl"].ToString());
                        oldNum = oldNum + Convert.ToDecimal(Rksl);
                        strSql = "UPDATE ipsjk set Rksl=" + oldNum + " where  Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Rksl>0";
                    }
                    else
                    {
                        //插入仓库
                        strSql = "insert into Ipsjk(Xh,Rq,Bm,Dwh,Dwmc,Pm,Gg,Rksl,Iksl,Jcsl,Dj,Rkje,Ikje,Jcje,Mbvl,Zy,Rkdh,Ikdh,Cfdd,Pvh,Xuf,Bzvu,Ixb1,Ixb2,Ixb3) values('" + Xh + "',date(" + Rq + "),'" + Bm.Substring(3, 6) + "','" + Dwh + "','" + Dwmc + "','" + Pm + "','" + Gg + "'," + Convert.ToDecimal(Rksl) + ",0,0,0,0,0,0,0,'','" + Rkdh + "','','','','','',0,0,'') ";
                    }
                    string strCon = ConfigurationManager.AppSettings["FOXIPKC"].ToString() + "IPSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    BusFoxProHelper.ExecuteNonQuery(strCon, CommandType.Text, strSql);
                }
                //出库
                else
                {
                    string Ywyh = "";
                    string Ywy = "";
                    string Qyh = "";
                    string Qymc = "";
                    string Fhr = "";
                    string Iksl = "";
                    string Je = "";
                    Xh = "";
                    string Ikdh = "";
                    string Dj = "";
                    EntityList<StockOutOrder> list2 = new EntityList<StockOutOrder>(this.model.GetDataAction());
                    list2.GetData(" ID=" + OrderId);
                    StockOutOrder sio = list2[0];
                    BusinessCustomer bc = new BusinessCustomer();
                    EntityList<BusinessCustomer> list3 = new EntityList<BusinessCustomer>(this.model.GetDataAction());
                    if (sio.CLIENTNO != "")
                        list3.GetData(" ID=" + sio.CLIENTNO);
                    if (list3.Count > 0)
                    {
                        bc = list3[0];
                    }
                    Bm = ms.Code;
                    Ywyh = user.ID.ToString().PadLeft(3, '0');
                    Ywy = user.name;
                    DataTable tempdt = this.model.GetDataAction().GetDataTable("select * from Acc_WMS_OutOrder where ID=" + OrderId);
                    if (tempdt.Rows.Count > 0) {
                        if (tempdt.Rows[0]["FREGIONID"].ToString() != "0")
                        {
                            EntityList<Region> listrn = new EntityList<Region>(this.model.GetDataAction());
                            listrn.GetData(" ID=" + tempdt.Rows[0]["FREGIONID"].ToString());
                            Qyh = listrn[0].ID.ToString().PadLeft(3, '0');
                            Qymc = listrn[0].RegionName;
                        }
                    }
                    Fhr = Rq;
                    Gg = ms.FNAME;
                    Dwh = bc.ID.ToString().PadLeft(4, '0');
                    Dwmc = bc.CUSTOMERNAME;
                    Pm = "鸭产品";
                    Iksl = (Convert.ToDecimal(SmNum)).ToString();
                    //if (IsReturn == "1") {
                    //    Iksl = (Convert.ToDecimal(SmNum) * (-1)).ToString();
                    //}
                    Ikdh = sio.Code;
                    Je = (ms.PRICE * Convert.ToDouble(SmNum)).ToString();
                    Dj = ms.PRICE.ToString();
                    Xh = Ikdh;
                    string strSql = "";
                    string strCon = "";
                    string strOldSql = "";
                    decimal oldNum = 0;
                    DataTable dtOldIpkc = null;
                    strCon = ConfigurationManager.AppSettings["FOXXG"].ToString() + "XUSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    strOldSql = "SELECT * from Xusjk where Fhr={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "' and Xh='" + Xh + "'";
                    dtOldIpkc = BusFoxProHelper.ExecuteDataTable(strCon, CommandType.Text, strOldSql);
                    oldNum = 0;
                    if (dtOldIpkc.Rows.Count > 0)
                    {
                        oldNum = Convert.ToDecimal(dtOldIpkc.Rows[0]["Sl"].ToString());
                        oldNum = oldNum + Convert.ToDecimal(Iksl);
                        //更新销管
                        strSql = "UPDATE Xusjk set Sl=" + oldNum + " where  Fhr={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "' and Xh='" + Xh + "'";

                    }
                    else
                    {
                        //插入销管
                        strSql = "insert into Xusjk(Xh,Bm,Ywyh,Ywy,Qyh,Qymc,Fhr,Dwh,Dwmc,Pm,Gg,Sl,Dj,Je,Fph,Til,Pvh,Mbvl,Xuti,Xufy,Jsfu,Shr,Hkr,Hkje,Qkje,Hhqk,Nbjg,Djie,Jgie,Bzvu,Jxrq,Xdju,Lxvi,Lxbl,Thyy,Uirq,Qyfz,Ixb1,Ixb2,Ixb3)  ";
                        strSql = strSql + "values('" + Xh + "','" + Bm.Substring(3, 6) + "','" + Ywyh + "','" + Ywy + "','" + Qyh + "','" + Qymc + "',date(" + Fhr + "),'" + Dwh + "','" + Dwmc + "','" + Pm + "','" + Gg + "'," + Iksl + "," + Dj + "," + Je + ",'" + Xh + "',0,'',0,0,0,'','',date(" + Fhr + "),0,0,0,0,0,0,'',date(" + Fhr + "),0,0,0,'',date(" + Fhr + "),'',0,0,'')";
                    }
                    BusFoxProHelper.ExecuteNonQuery(strCon, CommandType.Text, strSql);
                    strCon = ConfigurationManager.AppSettings["FOXIPKC"].ToString() + "IPSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    strOldSql = "SELECT * from IPSJK where Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Iksl>0 and Xh='" + Xh + "'";
                    dtOldIpkc = BusFoxProHelper.ExecuteDataTable(strCon, CommandType.Text, strOldSql);
                    oldNum = 0;
                    if (dtOldIpkc.Rows.Count > 0)
                    {
                        oldNum = Convert.ToDecimal(dtOldIpkc.Rows[0]["Iksl"].ToString());
                        oldNum = oldNum + Convert.ToDecimal(Iksl);
                        //更新仓库
                        strSql = "UPDATE IPSJK set Iksl=" + oldNum + " where  Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Iksl>0  and Xh='" + Xh + "'";
                    }
                    else
                    {
                        //插入仓库
                        strSql = "insert into Ipsjk(Xh,Rq,Bm,Dwh,Dwmc,Pm,Gg,Rksl,Iksl,Jcsl,Dj,Rkje,Ikje,Jcje,Mbvl,Zy,Rkdh,Ikdh,Cfdd,Pvh,Xuf,Bzvu,Ixb1,Ixb2,Ixb3) values('" + Xh + "',date(" + Rq + "),'" + Bm.Substring(3, 6) + "','" + Dwh + "','" + Dwmc + "','" + Pm + "','" + Gg + "',0," + Convert.ToDecimal(Iksl) + ",0,0,0,0,0,0,'',',','" + Ikdh + "','','','','',0,0,'') ";
                    }
                    BusFoxProHelper.ExecuteNonQuery(strCon, CommandType.Text, strSql);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        protected Materials ValidateStockMaterial(StockInfoMaterials sm, IDataAction acion)
        {

            Materials mmm = sm.GetForeignObject<Materials>(acion);
            if (mmm.BATCH)
            {
                if (string.IsNullOrEmpty(sm.BATCHNO))
                    throw new Exception("异常：物料" + mmm.FNAME + "为批管，批次号不能为空！");
            }
            else
                sm.BATCHNO = "";
            if (mmm.SEQUENCECODE)
            {
                //StockInfoMaterials sim = sm;
                if (sm.STAY5 == "qt")
                {
                    //代表是其他出库
                    if (sm.StockSequence.Count != sm.NUM && sm.StockSequence.Count > 0)
                        throw new Exception("异常：物料" + mmm.FNAME + "为序列码管理，序列码成员数量" + sm.StockSequence.Count + "与行数量" + sm.NUM + "不匹配！如要出库请添加匹配数量的单件码，或删除该物料" + sm.MCODE + "下对应的所有单件码");
                }
                else
                {
                    if (sm.StockSequence.Count <= 0)
                        throw new Exception("异常：物料" + mmm.FNAME + "为序列码管理，序列码不能为空！");

                }

            }
            return mmm;
        }
        protected WareHouse ValidateWareHouse(StockInfoMaterials sm, IDataAction acion)
        {
            WareHouse wh = null;
            EntityList<WareHouse> whlist = new EntityList<WareHouse>(acion);
            whlist.GetData("ID=" + sm.WAREHOUSEID);
            if (whlist.Count == 0)
                throw new Exception("异常：指定的仓库不存在！");
            wh = whlist[0];
            //if (!string.IsNullOrEmpty(sm.DEPOTWBS))
            //{
            //    wh.ChildItems.GetData("ID='" + sm.DEPOTWBS + "'");
            //    if (wh.ChildItems.Count <= 0)
            //        throw new Exception("异常：指定的存储位置" + sm.DEPOTWBS + "在" + wh.WAREHOUSENAME + "中不存在！");
            //}
            return wh;
        }

        public void putin(StockInfoMaterials sm, string controller, IDataAction acion, ControllerBase cbname)
        {
            UpdateInfoMaterials(sm, controller, acion, cbname);
        }
        /// <summary>
        /// 改变库存数量（重载）
        /// </summary>
        /// <param name="materialcode"></param>
        /// <param name="depot"></param>
        /// <param name="portno"></param>
        /// <param name="num"></param>
        public void putin(StockInfoMaterials sm, string controller, IDataAction acion)
        {
            UpdateInfoMaterials(sm, controller, acion, null);
            #region 不要
            ////string whereSql ="Code='" + sm.Code + "' and DEPOTWBS='" + sm.DEPOTWBS + "' and PORTCODE='"+sm.PORTCODE+" '";
            //string whereSql = "Code='" + sm.Code + "' and PORTCODE='" + sm.PORTCODE + " '";
            //whereSql += " and depotwbs in(select id from acc_wms_warehouse where type='" + sm.DEPOTWBS + "' OR id='" + sm.DEPOTWBS + "')";
            //if (sm.BATCHNO == null)
            //{
            //    whereSql += " and BATCHNO is null";
            //}
            //else if (sm.BATCHNO == "")
            //{
            //    whereSql += " and BATCHNO =''";
            //}
            //else
            //{
            //    whereSql += " and BATCHNO ='" + sm.BATCHNO + "'";
            //}
            //if (sm.SENBATCHNO == null)
            //{
            //    whereSql += " and SENBATCHNO is null";
            //}
            //else if (sm.SENBATCHNO == "")
            //{
            //    whereSql += " and SENBATCHNO =''";
            //}
            //else
            //{
            //    whereSql += " and SENBATCHNO ='" + sm.SENBATCHNO + "'";
            //}
            //EntityList<StockInfoMaterials> list1 = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
            //list1.GetData(whereSql);
            //if (controller == "出库")
            //{
            //    ////添加验证，如果启用质检那么出库时将判断产品库存状态是否符合出库
            //    if (m.ISCHECKPRO == true)
            //    {
            //        whereSql += " and ([STATUS]!='3' or [STATUS]!='1')";
            //    }
            //    ///如果有库存记录
            //    if (list1.Count > 0)
            //    {
            //        foreach (StockInfoMaterials item in list1)
            //        {
            //            if (!m.NUMSTATE)
            //            {
            //                if (item.NUM - (-sm.NUM) < 0)
            //                {
            //                    throw new Exception("商品编码：" + m.Code + ";    商品名称：" + m.FNAME + ";    出库数量大于库存数量" + item.NUM + "且产品不允许负库存");
            //                }
            //            }
            //            item.NUM = item.NUM - (-sm.NUM);
            //        }
            //    }
            //    else
            //    {
            //        if (m.NUMSTATE == true)
            //        {
            //            StockInfoMaterials sim = NewStockInfoMaterials(sm, m);
            //            list1.Add(sim);
            //        }
            //        else
            //        {
            //            throw new Exception("商品编码：" + m.Code + "    商品名称：" + m.FNAME + "    出库数量大于库存数量且产品不允许负库存");
            //        }
            //    }
            //    //更改托盘和货位状态
            //    if (list1.Count > 0)
            //    {
            //        foreach (StockInfoMaterials item in list1)
            //        {
            //            UpdatePortState(item);
            //            UpdateWarehouseState(item);
            //        }
            //    }
            //    StockInfoMaterials sims = new StockInfoMaterials();
            //    ///如果此入库信息所属仓库不允许0库存记录，那么每次都执行删除记录
            //    EntityList<WareHouse> wh = new EntityList<WareHouse>(this.model.GetDataAction());
            //    wh.GetData("id='" + sm.DEPOTWBS + "'");
            //    if (wh.Count > 0)
            //    {
            //        if (wh[0].ISDELSTATUS == false)
            //        {
            //            foreach (var item in list1)
            //            {
            //                if (item.NUM == 0)
            //                {
            //                    string sql = "delete from " + sims.ToString() + " where id='" + item.ID + "'";
            //                    IDataAction action = this.model.GetDataAction();
            //                    action.Execute(sql);
            //                }
            //            }
            //        }
            //    }
            //}
            //else if (controller == "入库")
            //{
            //    ////入库时添加状态条件
            //    if (m.ISCHECKPRO == true)
            //    {
            //        whereSql += " and STATUS='" + sm.STATUS + "'";
            //    }
            //    ////库存信息有此库存在数量上累加
            //    if (list1.Count > 0)
            //    {
            //        foreach (StockInfoMaterials item in list1)
            //        {
            //            sm.ID = item.ID;
            //            item.NUM = item.NUM + sm.NUM;

            //        }
            //    }
            //    ////没有此库存创建一个新的记录
            //    else
            //    {
            //        StockInfoMaterials sim = NewStockInfoMaterials(sm, m);
            //        list1.Add(sim);
            //    }
            //    if (list1.Count > 0)
            //    {
            //        foreach (StockInfoMaterials item in list1)
            //        {
            //            UpdatePortState(item);
            //            UpdateWarehouseState(item);
            //        }
            //    }
            //}

            //list1.Save();

            #endregion
        }

        private void UpdateInfoMaterials(StockInfoMaterials sm, string controller, IDataAction acion, ControllerBase cbname)
        {
            string stay5 = sm.STAY5;
            if (sm == null)
                throw new Exception("异常：库存实体不能为空！");
            if (string.IsNullOrEmpty(sm.Code))
                throw new Exception("异常：物料ID不能为空！");
            if (sm.WAREHOUSEID <= 0)
                throw new Exception("异常：仓库ID不能为空！");
            Materials mmm = ValidateStockMaterial(sm, acion);
            WareHouse stock = ValidateWareHouse(sm, acion);
            string w = "code='" + sm.Code + "' and WAREHOUSEID='" + sm.WAREHOUSEID + "'";
            if (!string.IsNullOrEmpty(sm.BATCHNO))
                w += " and BATCHNO='" + sm.BATCHNO + "'";
            if (!string.IsNullOrEmpty(sm.DEPOTWBS))
                w += " and DEPOTWBS='" + sm.DEPOTWBS + "'";
            if (!string.IsNullOrEmpty(sm.PORTCODE) && sm.PORTCODE != "0")
                w += " and PORTCODE='" + sm.PORTCODE + "'";
            if (!string.IsNullOrEmpty(sm.SENBATCHNO))
                w += " and SENBATCHNO='" + sm.SENBATCHNO + "'";
            EntityList<StockInfoMaterials> list = new EntityList<StockInfoMaterials>(acion);
            list.GetData(w);
            InfoInSequence seq = new InfoInSequence();
            string seqtn = seq.ToString();
            string hw = "";
            if (!string.IsNullOrEmpty(sm.DEPOTWBS))
                hw = "货位：" + sm[sm.GetAppendPropertyKey("DEPOTWBS")].ToString();
            string tp = "";
            if (!string.IsNullOrEmpty(sm.PORTCODE) && sm.PORTCODE != "0")
                tp = "托盘：" + sm[sm.GetAppendPropertyKey("PORTCODE")].ToString();
            string pc = "";
            if (!string.IsNullOrEmpty(sm.BATCHNO))
                pc = "批次：" + sm.BATCHNO;
            string msg = "物料" + mmm.FNAME + "(编码：" + mmm.Code + "" + pc + ")在" + stock.WAREHOUSENAME + "的指定位置(" + hw + tp + ")";
            if (controller == "入库")
            {
                if (list.Count > 0)
                {
                    StockInfoMaterials sm1 = list[0];
                    sm1.NUM = sm1.NUM + sm.NUM;
                    if (mmm.SEQUENCECODE)
                    {
                        string sql = "select SEQUENCECODE from " + seqtn + " where SEQUENCECODE='{0}'";
                        object obj = null;
                        if (sm.StockSequence.Count == 0)
                        {
                            sm.StockSequence.DataAction = acion;
                            sm.StockSequence.GetData();
                        }
                        foreach (InfoInSequence iis in sm.StockSequence)
                        {
                            obj = acion.GetValue(string.Format(sql, iis.SEQUENCECODE));
                            if (obj == null || string.IsNullOrEmpty(obj.ToString()))
                                sm1.StockSequence.Add(iis);
                            else
                            {
                                throw new Exception("异常：序列码" + iis.SEQUENCECODE + "在库存中已存在，不能入库！");
                            }
                        }
                    }
                }
                else
                {
                    if (!mmm.SEQUENCECODE)
                        sm.StockSequence.Clear();
                    list.Add(sm);
                }
                ((IEntityCommand)list).Save(acion);
                if (!string.IsNullOrEmpty(sm.PORTCODE))
                {
                    string portno = " id BETWEEN 1212 AND 1226";
                    string upprot = "update " + new Ports().ToString() + " set STATUS=1 where " + portno + " and ID=" + sm.PORTCODE;
                    acion.Execute(upprot);
                }
            }
            if (controller == "出库")
            {
                if (list.Count > 0)
                {
                    StockInfoMaterials sm1 = list[0];
                    if (stay5 != "qt")
                    {
                        string status1 = "SELECT a.ID, CASE WHEN CAST(DATEDIFF(dd, a.LASTINTIME,GETDATE()) AS INTEGER) <= ISNULL(b.shelflife, 0) THEN '否'WHEN ISNULL(b.shelflife, 0) > 0 AND CAST(DATEDIFF(dd, a.LASTINTIME,GETDATE()) AS INTEGER) > ISNULL(b.shelflife,0) THEN '是' ELSE '否' END AS status1 FROM dbo.Acc_WMS_InfoMaterials a INNER JOIN dbo.Acc_Bus_BusinessCommodity b ON a.Code= b.ID where a.id='" + sm1.ID + "'";
                        DataTable dtStatus = acion.GetDataTable(status1);
                        if (dtStatus.Rows[0]["status1"].ToString() == "是")
                        {
                            throw new Exception("异常：" + msg + "指定出库" + sm.NUM + "库存数" + (sm1.NUM + sm.NUM) + "的产品已过有效期请复检合格后出库！（或使用其他出库进行出库）");
                        }
                    }
                    sm1.NUM = sm1.NUM - sm.NUM;
                    if (sm1.NUM < 0)
                    {
                        if (!mmm.NUMSTATE)
                            throw new Exception("异常：" + msg + "指定出库" + sm.NUM + "库存数" + (sm1.NUM + sm.NUM) + "库存数量不足不能出库！");
                    }
                    if (sm1.NUM == 0)
                        list.Remove(sm1);

                    if (mmm.SEQUENCECODE)
                    {
                        string del = "delete from " + seqtn + " where SEQUENCECODE='{0}'";
                        string sql = "select SEQUENCECODE from " + seqtn + " where SEQUENCECODE='{0}'";
                        object obj = null;
                        foreach (InfoInSequence iis in sm.StockSequence)
                        {
                            obj = acion.GetValue(string.Format(sql, iis.SEQUENCECODE));
                            if (obj != null && !string.IsNullOrEmpty(obj.ToString()))
                                acion.Execute(string.Format(del, iis.SEQUENCECODE));
                            else
                                throw new Exception("异常：" + msg + "序列码" + iis.SEQUENCECODE + "不存在,不能出库！");
                        }
                    }
                    //}
                    ((IEntityCommand)list).Save(acion);
                    if (!string.IsNullOrEmpty(sm.PORTCODE))
                    {
                        string upprot = "update " + new Ports().ToString() + " set STATUS=0 where ID=" + sm.PORTCODE;
                        acion.Execute(upprot);
                    }
                }
                else
                {

                    throw new Exception("异常：" + msg + "不存在不能出库!");
                }
            }
            return;
        }

        /// <summary>
        /// 更改托盘状态
        /// </summary>
        /// <param name="sim"></param>
        public void UpdatePortState(StockInfoMaterials sim)
        {
            if (sim.NUM == 0.00)
            {
                EntityList<StockInfoMaterials> listinfo = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
                listinfo.GetData("PORTCODE='" + sim.PORTCODE + "' and ID<>" + sim.ID);
                if (listinfo.Count == 0)
                {
                    EntityList<Ports> listPort = new EntityList<Ports>(this.model.GetDataAction());
                    listPort.GetData("ID=" + sim.PORTCODE);
                    if (listPort[0].STATUS == "1")
                        listPort[0].STATUS = "0";
                    else
                        listPort[0].STATUS = "1";
                    listPort.Save();
                }
            }
        }

        /// <summary>
        /// 更改货位状态
        /// </summary>
        /// <param name="sim"></param>
        public void UpdateWarehouseState(StockInfoMaterials sim)
        {
            if (sim.NUM == 0.00)
            {
                EntityList<StockInfoMaterials> listinfo = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
                listinfo.GetData("DEPOTWBS='" + sim.DEPOTWBS + "' and ID<>" + sim.ID);
                if (listinfo.Count == 0)
                {
                    EntityList<WareHouse> listWarehouse = new EntityList<WareHouse>(this.model.GetDataAction());
                    listWarehouse.GetData("ID=" + sim.DEPOTWBS);
                    if (listWarehouse[0].STATUS == "1")
                        listWarehouse[0].STATUS = "0";
                    else
                        listWarehouse[0].STATUS = "1";
                    listWarehouse.Save();
                }
            }
        }

        /// <summary>
        /// 没有库存记录，出入库都需要创建个新库存记录
        /// </summary>
        /// <param name="sm"></param>
        /// <param name="m"></param>
        /// <returns></returns>
        private static StockInfoMaterials NewStockInfoMaterials(StockInfoMaterials sm, Materials m)
        {
            StockInfoMaterials sim = new StockInfoMaterials();
            sim = sm;
            sim.ISLOCK = false;
            sim.LASTINTIME = DateTime.Now;
            //if (m.ISCHECKPRO == true)
            //{
            //    sim.STATUS = "1";////待检验
            //}
            //else
            //{
            //    sim.STATUS = "4";////免检验
            //}
            return sim;
        }

        private string CheckPutInData(string strcontroller)
        {

            EntityList<Ports> list1 = new EntityList<Ports>(this.model.GetDataAction());
            list1.GetData(" ID='" + SmPortcode + "'");
            if (list1.Count == 0)
                return "系统无此托盘！";
            else
            {
                Ports ps = list1[0];
                if (strcontroller == "0")
                {
                    if (ps.STATUS == "1")
                        return "此托盘处于占用状态，不能进行扫描！";
                }
            }
            if (SmCode == null || SmCode == "")
                return "请选择物料！";
            return "Y";
        }
        /// <summary>
        /// 初始化显示外键查询库存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="data"></param>
        public static void OnInitForeignStockInfoMaterials(StockOutOrderMaterials model, InitData data)
        {
            StockInfoView v = new StockInfoView();
            data.modeldata = ((IModel)v).GetModelData();
            data.modeldata.title = "库存产品表";
            foreach (ItemData d in data.modeldata.childitem)
            {
                d.visible = false;
                if (d.IsField("WAREHOUSENAME") || d.IsField("MNAME") ||
                d.IsField("model") || d.IsField("BATCHNO") || d.IsField("SUBNO") || d.IsField("DCODE") || d.IsField("KYNUM") || d.IsField("NUM") || d.IsField("ZYNUM"))
                    d.visible = true;
            }
        }
        /// <summary>
        /// 初始化显示外键查询库存数据
        /// </summary>
        /// <param name="model"></param>
        /// <param name="data"></param>
        public static void OnInitForeignStockInfoMaterials(MoveOrderMaterials model, InitData data)
        {
            StockInfoView v = new StockInfoView();
            data.modeldata = ((IModel)v).GetModelData();
            data.modeldata.title = "库存产品表";
            foreach (ItemData d in data.modeldata.childitem)
            {
                d.visible = false;
                if (d.IsField("MNAME") || d.IsField("MCODE") || d.IsField("WAREHOUSENAME") || d.IsField("DCODE") ||
                    d.IsField("MODEL") || d.IsField("BATCHNO") || d.IsField("SUBNO") || d.IsField("NUM"))
                    d.visible = true;
            }
        }



        /// <summary>
        /// 得到最佳货位
        /// </summary>
        /// <returns></returns>
        [WhereParameter]
        public string BMaterialID { get; set; }
        public void GetBestInDepot()
        {
            string returnstr = "";
            IDataAction action = this.model.GetDataAction();
            string strSql = "select substring(b.Code,1,2) wbsCodes,COUNT(*) intsum  from Acc_WMS_InfoMaterials a left join Acc_WMS_WareHouse b on a.DEPOTWBS=b.ID ";//and substring(b.Code,1,2)='" + BWareHouse + "'
            strSql = strSql + "where a.Code=" + BMaterialID + " and substring(b.Code,3,2)not in ('96','97','98','99')   group by substring(b.Code,1,2)";
            //先判断该产品在没在库存里
            DataTable dt = action.GetDataTable(strSql);
            //如果返回的table里的行数为0则库里没有该产品,则在新的行里推荐第一个货位
            if (dt.Rows.Count == 0)
            {
                strSql = "select * from Acc_WMS_WareHouse b  where STATUS='0'  and substring(b.Code,3,2)not in ('96','97','98','99') and ID not in (select DEPOTWBS from Acc_WMS_InfoMaterials) and substring(b.Code,6,1)='1'  and substring(b.Code,8,1)='1' order by substring(b.Code,1,2),substring(b.Code,3,2),substring(b.Code,5,2),substring(b.Code,7,2)";
                dt = action.GetDataTable(strSql);
                if (dt.Rows.Count > 0)
                    throw new Exception(dt.Rows[0]["WAREHOUSENAME"].ToString());
                else
                    throw new Exception("该入库仓库已经没有新的行可以推荐，请手动输入货位！");
            }
            else
            {
                //intsum = -1说明表中列的值都是24
                int intsum = -1;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strWare = dt.Rows[i]["wbsCodes"].ToString();
                    strSql = "select substring(b.Code,1,4) wbsCodes,COUNT(*) intsum  from Acc_WMS_InfoMaterials a left join  Acc_WMS_WareHouse b  on a.DEPOTWBS=b.ID  where a.Code='" + BMaterialID + "'  and  substring(b.Code,3,2)not in ('96','97','98','99')  and substring(b.Code,1,2)='" + strWare + "'  group by substring(b.Code,1,4)";
                    DataTable dta = action.GetDataTable(strSql);
                    for (int l = 0; l < dta.Rows.Count; l++)
                    {
                        if (dta.Rows[0]["intsum"].ToString() != "24")
                        {
                            //选出货位为空，并且编码前4为0*0*的，这样就确定行了
                            strSql = "select * from Acc_WMS_WareHouse  where status='0' and substring(Code,1,2)='" + strWare + "' and substring(Code,1,4)='" + dta.Rows[l]["wbsCodes"].ToString() + "' and substring(Code,8,1)<>'0'  order by substring(Code,5,4)";
                            DataTable dtb = action.GetDataTable(strSql);
                            if (dtb.Rows.Count == 0)
                            {
                                strSql = "select * from Acc_WMS_WareHouse  where status='0' and substring(Code,1,2)='" + strWare + "' and substring(Code,3,2)not in ('96','97','98','99') and substring(Code,6,1)='1'  and substring(Code,8,1)='1'  order by substring(Code,3,2),substring(Code,5,2),substring(Code,7,2)";
                                DataTable dtc = action.GetDataTable(strSql);
                                if (dtc.Rows.Count > 0)
                                {
                                    throw new Exception(dtc.Rows[0]["WAREHOUSENAME"].ToString());
                                }
                                else
                                    throw new Exception("该仓库货位已经用完！");
                            }
                            else
                            {
                                returnstr = dtb.Rows[0]["WAREHOUSENAME"].ToString();
                                throw new Exception(returnstr);
                            }
                        }
                    }
                }
                //是-1的话则选出新的一行
                if (intsum == -1)
                {
                    strSql = "select * from Acc_WMS_WareHouse  where status='0' and substring(Code,1,2)='" + dt.Rows[0]["wbsCodes"].ToString() + "' and substring(Code,3,2)not in ('96','97','98','99') and substring(Code,6,1)='1'  and substring(Code,8,1)='1' order by substring(Code,3,2),substring(Code,5,2),substring(Code,7,2)";
                    DataTable dtd = action.GetDataTable(strSql);
                    if (dtd.Rows.Count > 0)
                    {
                        throw new Exception(dtd.Rows[0]["WAREHOUSENAME"].ToString());
                    }
                    else
                        throw new Exception("该仓库货位已经用完！");
                }

            }

        }
        /// <summary>
        /// 得到出库最佳货位
        /// </summary>
        public void GetBestOutDepot()
        {
            EntityList<StockInfoMaterials> list1 = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
            list1.GetData(" CODE='" + BMaterialID + "' and DEPOTWBS='7066'");
            if (list1.Count > 0)
            {
                EntityList<WareHouse> listwh = new EntityList<WareHouse>(this.model.GetDataAction());
                listwh.GetData(" ID=" + list1[0].DEPOTWBS);
                if (listwh.Count > 0)
                    throw new Exception(listwh[0].WAREHOUSENAME);
                else
                    throw new Exception("无");
            }
            else
            {
                IDataAction action = this.model.GetDataAction();
                string strSql = "select * from Acc_WMS_InfoMaterials  where Code='" + BMaterialID + "' order by LASTINTIME";
                DataTable dtd = action.GetDataTable(strSql);
                if (dtd.Rows.Count > 0)
                {
                    EntityList<WareHouse> listwh = new EntityList<WareHouse>(this.model.GetDataAction());
                    listwh.GetData(" ID=" + dtd.Rows[0]["DEPOTWBS"].ToString());
                    if (listwh.Count > 0)
                        throw new Exception(listwh[0].WAREHOUSENAME);
                    else
                        throw new Exception("无");
                }
                throw new Exception("无");
            }
        }

        /// 库存表senbatchno(sm.senbatchno)
        [WhereParameter]
        public string OutOrderId { get; set; }
        /// 库存表Num(sm.Num)
        [WhereParameter]
        public string OutOrderMaterialID { get; set; }
        /// controller(0:入库，1：出库)
        [WhereParameter]
        public string OutNum { get; set; }
        public string SetOutNum()
        {

            EntityList<StockOutOrderOutNum> sooo = new EntityList<StockOutOrderOutNum>(this.model.GetDataAction());
            sooo.GetData("ORDERNO='" + OutOrderId + "' and MATERIALNO='" + OutOrderMaterialID + "'");
            if (sooo.Count > 0)
            {
                StockOutOrderOutNum aaa = sooo[0];
                aaa.NUM = aaa.NUM + Convert.ToDouble(OutNum);
                aaa.PORTNUM = aaa.PORTNUM + 1;
            }
            else
            {
                StockOutOrderOutNum soo1 = new StockOutOrderOutNum();
                soo1.ORDERNO = OutOrderId;
                soo1.MATERIALNO = OutOrderMaterialID;
                soo1.NUM = Convert.ToDouble(OutNum);
                soo1.PORTNUM = 1;
                sooo.Add(soo1);
            }
            sooo.Save();
            return "Y";
        }
        public void GetOutNum()
        {
            EntityList<StockOutOrderOutNum> sooo = new EntityList<StockOutOrderOutNum>(this.model.GetDataAction());
            sooo.GetData("ORDERNO='" + OutOrderId + "' and MATERIALNO='" + OutOrderMaterialID + "'");
            if (sooo.Count > 0)
            {
                StockOutOrderOutNum aaa = sooo[0];
                throw new Exception(aaa.NUM.ToString());
            }
            else
            {
                throw new Exception("0");
            }
        }
    }
}
